package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.common.R;
import com.blog.domain.Swipe;
import com.blog.service.ISwipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @AUTHOR:HZG MADE IN CHINA
 */
@RestController
@RequestMapping("/swipes")
public class SwipeController {
    @Autowired
    private ISwipeService swipeService;


    /**
     * 新增swipe
     *
     * @param swipe
     * @return
     */
    @PostMapping("/add")
    public R<Swipe> save(@RequestBody Swipe swipe) {

        swipeService.save(swipe);

        return R.success(swipe, "新增轮播图成功");
    }

    /**
     * 根据id轮播图
     *
     * @param user_id
     * @return
     */
    @GetMapping("/show/{user_id}")
    public R<List<Swipe>> get(@PathVariable Integer user_id) {
        LambdaQueryWrapper<Swipe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Swipe::getUserId, user_id);
        List<Swipe> swipes = swipeService.list(queryWrapper);
        if (swipes.isEmpty()) {
            return R.error("查询失败");
        }
        return R.success(swipes, "查询成功");
    }




    /**
     * 修改轮播图信息
     *
     * @param swipe
     * @return
     */

    @PutMapping("/modify")
    public R update(@RequestBody Swipe swipe) {

        //根据页面提交的swipeid查询数据库
        LambdaQueryWrapper<Swipe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Swipe::getSwipeId, swipe.getSwipeId());
        Swipe mSwipe = swipeService.getOne(queryWrapper);


        if (mSwipe == null) {
            return R.error("ID不存在");
        }
        mSwipe.setImgSrc(swipe.getImgSrc());
        mSwipe.setTitle(swipe.getTitle());
        mSwipe.setInstruction(swipe.getInstruction());

        swipeService.updateById(mSwipe);

        return R.success(mSwipe, "修改成功");
    }

    /**
     * 根据id删除swipe
     * @param swipeId
     * @return
     */
    @DeleteMapping("/delete/{swipeId}")
    public R<String> delete(@PathVariable Integer swipeId){



        //根据页面提交的swipeid查询数据库
        LambdaQueryWrapper<Swipe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Swipe::getSwipeId,swipeId );
        Swipe mSwipe = swipeService.getOne(queryWrapper);


        if (mSwipe == null) {
            return R.error("ID不存在");
        }

        swipeService.removeById(swipeId);

        return R.success("轮播图删除成功");
    }

}
